package com.java.tutorials.designpattern.behavioral.template.bubblesorter;

/**
 * Created by xuzhike on 2016/3/13.
 */
//使用模板模式可以分隔冒泡排序的方法进一个抽象类,而让它的子类具体实现Swap和
//outOfOrder方法,可以扩展不同对象采用同样冒泡排序法算法:
//冒泡排序算法模板类:
public abstract class BubbleSorter {
    private int operations = 0;
    protected int length = 0;
    protected int doSort () {
        operations = 0;
        if (length <= 1)
            return operations;
        for (int nextToLast = length - 2;
             nextToLast >= 0; nextToLast--)
            for (int index = 0; index <= nextToLast; index++) {
                if (outOfOrder (index))
                    swap (index);
                operations++;
            }
        return operations;
    }
    //前后数据转换位置
    protected abstract void swap (int index);
    //检查前者数据是不是大于后者数据
    protected abstract boolean outOfOrder (int index);
}
